#!/usr/bin/perl
# 2014/06/02 Categorize each binding peaks to several properties

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [summits bed file] -o [categorized file]\n";
}

my %opt;
getopts("i:o:", \%opt);
my $FILE_in = $opt{i};
my $FILE_out = $opt{o};

my $DATA_DIR = '/cscb/noma_nfs/Data/S.Pombe_seq/pombase_ASM294v1.18/contig/';
my $FILE_tRNA = $DATA_DIR . 'tRNA.bed';
my $FILE_LTR = $DATA_DIR . 'LTR.bed';
my $FILE_5SrRNA = $DATA_DIR . '5SrRNA-rDNA.bed';
my $FILE_high = $DATA_DIR . 'high_expressed_gene_100.bed';
my $FILE_ribosomal = $DATA_DIR . 'ribosomal_gene.bed';
my $FILE_SPNCRNA = $DATA_DIR . 'SPNCRNA.bed';
my $FILE_SPSNORNA = $DATA_DIR . 'SPSNORNA.bed';
my $FILE_SPSNRNA = $DATA_DIR . 'SPSNRNA.bed';

my $PROJECT_DIR = '/cscb/noma_nfs/Project/2014-04-30_ChIA-PET_rad21_biological_replica/out/';
my $FILE_class1 = $PROJECT_DIR . '2014-05-28_gene_direction_definition_class1.txt';
my $FILE_class2 = $PROJECT_DIR . '2014-05-28_gene_direction_definition_class2.txt';
my $FILE_other = $PROJECT_DIR . '2014-05-28_gene_direction_definition_other.txt';

my %DEF;
&readDef($FILE_tRNA, 'tRNA');
&readDef($FILE_LTR, 'LTR');
&readDef($FILE_5SrRNA, '5SrRNA');
&readDef($FILE_high, 'high');
&readDef($FILE_ribosomal, 'ribosomal');
&readDef($FILE_SPNCRNA, 'SPNCRNA');
&readDef($FILE_SPSNORNA, 'SPSNORNA');
&readDef($FILE_SPSNRNA, 'SPSNRNA');
&readDef($FILE_class1, 'conv_class1');
&readDef($FILE_class2, 'conv_class2');
&readDef($FILE_other, 'conv_other');

sub readDef{
	my ($FILE, $category) = @_;
	my $fh_in = IO::File->new($FILE) or die "cannot open $FILE: $!";
	while($_ = $fh_in->getline()){
		s/\r?\n//;
		my ($chr, $start, $end, $name, $num, $direction) = split /\t/;
		$start -= 1500;
		$end = $start + 2999;
		for(my $i = $start; $i <= $end; $i++){
			push @{$DEF{$chr}{$i}}, $category;
		}
	}
	$fh_in->close();
}



my $fh_in = IO::File->new($FILE_in) or die "cannot open $FILE_in: $!";
my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
while($_ = $fh_in->getline()){
	s/\r?\n//;
	my ($chr, $start, $end, $name, $val) = split /\t/;
	my %OVERLAP_CHECK;
	for(my $i = $start; $i <= $end; $i++){
		if(exists $DEF{$chr}{$i}){
			foreach my $key(@{$DEF{$chr}{$i}}){
				$OVERLAP_CHECK{$key} = 1;
			}
		}
	}
	$fh_out->print("$name");
	foreach my $key(keys %OVERLAP_CHECK){
		$fh_out->print("\t$key");
	}
	$fh_out->print("\n");
}
$fh_out->close();
$fh_in->close();

